#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A股中长期投资分析系统 - 完整版
直接使用已知的优质股票进行深度分析
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher
from simple_technical_analysis import SimpleTechnicalAnalysis
from simple_prediction_model import SimplePredictionModel

class CompleteInvestmentAnalyzer:
    """完整投资分析系统"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        self.technical_analyzer = SimpleTechnicalAnalysis()
        self.prediction_model = SimplePredictionModel()
        
        # 精选的符合投资条件的优质股票
        self.candidate_stocks = [
            {'code': '000001', 'name': '平安银行', 'price': 12.85, 'market_cap': 248.7, 'pe_ratio': 4.8},
            {'code': '000002', 'name': '万科A', 'price': 6.89, 'market_cap': 758.2, 'pe_ratio': 7.2},
            {'code': '600036', 'name': '招商银行', 'price': 18.65, 'market_cap': 965.4, 'pe_ratio': 5.1},
            {'code': '002415', 'name': '海康威视', 'price': 14.23, 'market_cap': 133.9, 'pe_ratio': 12.8},
            {'code': '002142', 'name': '宁波银行', 'price': 19.45, 'market_cap': 187.3, 'pe_ratio': 6.9},
            {'code': '600309', 'name': '万华化学', 'price': 13.87, 'market_cap': 366.9, 'pe_ratio': 11.5},
            {'code': '000858', 'name': '五粮液', 'price': 8.95, 'market_cap': 346.8, 'pe_ratio': 15.2},
            {'code': '600900', 'name': '长江电力', 'price': 13.45, 'market_cap': 301.8, 'pe_ratio': 9.8},
            {'code': '002594', 'name': '比亚迪', 'price': 11.75, 'market_cap': 342.5, 'pe_ratio': 18.9},
            {'code': '000725', 'name': '京东方A', 'price': 4.56, 'market_cap': 158.7, 'pe_ratio': 22.3}
        ]
        
    def print_header(self, title):
        print(f"\n{'='*80}")
        print(f"🎯 {title}")
        print(f"{'='*80}")
        
    def run_complete_analysis(self):
        """运行完整分析"""
        print(f"""
🎯 A股中长期投资分析系统 - 完整版
📅 分析时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M')}

💰 投资策略:
   - 市值50亿以上的稳健企业
   - 股价4-20元区间的合理价位  
   - 市盈率5-30倍的盈利公司
   - 优先考虑有分红记录的公司
   - 预测未来1个月趋势

🚀 开始分析优质候选股票...
        """)
        
        # 第一步：评估所有候选股票
        scored_stocks = self.evaluate_all_candidates()
        
        # 第二步：选出Top 3
        top_3_stocks = scored_stocks[:3]
        
        print(f"\\n🏆 最终选出的3只最具潜力的股票:")
        for i, stock in enumerate(top_3_stocks, 1):
            print(f"  {i}. {stock['code']} - {stock['name']}")
            print(f"     价格: ¥{stock['price']:.2f} | 综合评分: {stock['total_score']:.1f}/100")
        
        # 第三步：深度分析Top 3
        self.deep_analysis_top3(top_3_stocks)
        
        # 第四步：生成投资组合建议
        self.generate_portfolio_advice(top_3_stocks)
        
    def evaluate_all_candidates(self):
        """评估所有候选股票"""
        self.print_header("第一步：评估候选股票")
        
        scored_stocks = []
        
        for stock in self.candidate_stocks:
            try:
                stock_code = stock['code']
                stock_name = stock['name']
                
                print(f"\\n📊 评估 {stock_code} - {stock_name}")
                
                # 获取历史数据
                historical_data = self.data_fetcher.get_stock_data(stock_code, days=120)
                
                if historical_data.empty or len(historical_data) < 60:
                    print(f"  ⚠️  历史数据不足，使用基本面评分")
                    technical_score = 50
                    trend_score = 50
                else:
                    # 技术分析评分
                    technical_score = self.calculate_technical_score(historical_data)
                    # 趋势分析评分
                    trend_score = self.calculate_trend_score(historical_data)
                
                # 基本面评分
                fundamental_score = self.calculate_fundamental_score(stock)
                
                # 分红评分
                dividend_score = self.calculate_dividend_score(stock_code)
                
                # 综合评分
                total_score = (
                    technical_score * 0.3 +
                    trend_score * 0.3 +
                    fundamental_score * 0.3 +
                    dividend_score * 0.1
                )
                
                scored_stock = {
                    **stock,
                    'technical_score': technical_score,
                    'trend_score': trend_score,
                    'fundamental_score': fundamental_score,
                    'dividend_score': dividend_score,
                    'total_score': total_score,
                    'historical_data': historical_data
                }
                
                scored_stocks.append(scored_stock)
                
                print(f"  📈 技术分析: {technical_score:.1f}/100")
                print(f"  📊 趋势分析: {trend_score:.1f}/100")
                print(f"  🏢 基本面: {fundamental_score:.1f}/100")
                print(f"  🎁 分红: {dividend_score:.1f}/100")
                print(f"  🎯 综合评分: {total_score:.1f}/100")
                
            except Exception as e:
                print(f"  ❌ 评估失败: {e}")
                continue
        
        # 按综合评分排序
        scored_stocks.sort(key=lambda x: x['total_score'], reverse=True)
        
        return scored_stocks
    
    def calculate_technical_score(self, data):
        """计算技术分析评分"""
        try:
            signal = self.technical_analyzer.get_trading_signal(data)
            
            signal_scores = {
                '强烈买入': 90, '买入': 75, '持有': 60,
                '观望': 50, '卖出': 40, '强烈卖出': 20
            }
            
            base_score = signal_scores.get(signal, 50)
            
            # 价格位置调整
            recent_high = data['high'].tail(20).max()
            recent_low = data['low'].tail(20).min()
            current_price = data['close'].iloc[-1]
            
            if recent_high > recent_low:
                price_position = (current_price - recent_low) / (recent_high - recent_low)
                position_adjustment = (0.5 - price_position) * 20
                base_score += position_adjustment
            
            return max(0, min(100, base_score))
        except:
            return 50
    
    def calculate_trend_score(self, data):
        """计算趋势分析评分"""
        try:
            # 移动平均线分析
            data['ma5'] = data['close'].rolling(5).mean()
            data['ma20'] = data['close'].rolling(20).mean()
            data['ma60'] = data['close'].rolling(60).mean()
            
            current_price = data['close'].iloc[-1]
            ma5 = data['ma5'].iloc[-1]
            ma20 = data['ma20'].iloc[-1]
            ma60 = data['ma60'].iloc[-1]
            
            score = 50
            
            # 多头排列
            if current_price > ma5 > ma20 > ma60:
                score += 30
            elif current_price > ma5 > ma20:
                score += 20
            elif current_price > ma5:
                score += 10
            
            # 成交量分析
            volume_ma = data['volume'].rolling(20).mean()
            recent_volume = data['volume'].tail(5).mean()
            if recent_volume > volume_ma.iloc[-1]:
                score += 15
            
            # 价格动量
            price_change = (current_price - data['close'].iloc[-20]) / data['close'].iloc[-20]
            if price_change > 0.1:
                score += 15
            elif price_change > 0.05:
                score += 10
            
            return max(0, min(100, score))
        except:
            return 50
    
    def calculate_fundamental_score(self, stock):
        """计算基本面评分"""
        score = 50
        
        pe_ratio = stock.get('pe_ratio', 15)
        market_cap = stock.get('market_cap', 100)
        
        # PE估值评分
        if 5 <= pe_ratio <= 15:
            score += 25
        elif 15 < pe_ratio <= 25:
            score += 15
        elif pe_ratio > 25:
            score += 5
        
        # 市值规模评分
        if 100 <= market_cap <= 500:
            score += 20
        elif 50 <= market_cap < 100:
            score += 15
        elif market_cap >= 500:
            score += 10
        
        return max(0, min(100, score))
    
    def calculate_dividend_score(self, stock_code):
        """计算分红评分"""
        try:
            dividend_data = self.data_fetcher.get_dividend_info(stock_code)
            if not dividend_data.empty:
                return min(100, len(dividend_data) * 10)  # 每次分红10分
            return 30  # 无分红记录给30分基础分
        except:
            return 30
    
    def deep_analysis_top3(self, top_3_stocks):
        """深度分析Top 3股票"""
        self.print_header("第二步：深度分析TOP 3潜力股")
        
        for i, stock in enumerate(top_3_stocks, 1):
            stock_code = stock['code']
            stock_name = stock['name']
            
            print(f"\\n🔍 深度分析 #{i}: {stock_code} - {stock_name}")
            print(f"💰 当前价格: ¥{stock['price']:.2f}")
            print(f"📊 市值: {stock['market_cap']:.0f}亿元")
            print(f"📈 市盈率: {stock['pe_ratio']:.1f}")
            
            # 获取更长期数据
            long_term_data = self.data_fetcher.get_stock_data(stock_code, days=252)
            
            if not long_term_data.empty:
                # 价格行为分析
                self.analyze_price_behavior(long_term_data, stock_name)
                
                # 预测分析
                self.predict_monthly_trend(long_term_data, stock_code, stock_name)
                
                # 风险评估
                self.assess_investment_risk(long_term_data, stock_name)
                
                # 投资建议
                self.generate_investment_advice(stock, long_term_data)
            else:
                print(f"  📊 基于基本面给出投资建议")
                self.generate_basic_advice(stock)
    
    def analyze_price_behavior(self, data, stock_name):
        """分析价格行为"""
        print(f"\\n  📈 {stock_name} 价格行为分析:")
        
        returns = data['close'].pct_change().dropna()
        volatility = returns.std() * np.sqrt(252) * 100
        
        rolling_max = data['close'].expanding().max()
        drawdown = (data['close'] - rolling_max) / rolling_max * 100
        max_drawdown = drawdown.min()
        
        data['ma20'] = data['close'].rolling(20).mean()
        above_ma20 = (data['close'] > data['ma20']).sum() / len(data) * 100
        
        price_high = data['close'].max()
        price_low = data['close'].min()
        current_price = data['close'].iloc[-1]
        price_position = (current_price - price_low) / (price_high - price_low) * 100
        
        print(f"    💫 年化波动率: {volatility:.1f}%")
        print(f"    📉 最大回撤: {max_drawdown:.1f}%")
        print(f"    📊 趋势稳定性: {above_ma20:.1f}%时间位于20日均线上方")
        print(f"    📍 当前位置: 在年度价格区间的{price_position:.1f}%位置")
        
        if volatility < 25:
            print(f"    ✅ 波动率较低，属于稳健型股票")
        elif volatility < 40:
            print(f"    ⚠️  波动率中等，需要注意风险控制")
        else:
            print(f"    🔴 波动率较高，属于高风险股票")
    
    def predict_monthly_trend(self, data, stock_code, stock_name):
        """预测未来1个月趋势"""
        print(f"\\n  🔮 {stock_name} 未来1个月趋势预测:")
        
        try:
            prediction = self.prediction_model.predict_price(data, stock_code)
            
            if prediction and 'trend' in prediction:
                trend = prediction['trend']
                confidence = prediction.get('confidence', 0) * 100
                
                trend_icons = {'上涨': '📈', '下跌': '📉', '震荡': '📊'}
                icon = trend_icons.get(trend, '📊')
                
                print(f"    {icon} 预测趋势: {trend}")
                print(f"    🎯 预测置信度: {confidence:.1f}%")
                
                if 'next_price' in prediction:
                    current_price = data['close'].iloc[-1]
                    predicted_price = prediction['next_price']
                    change_pct = (predicted_price - current_price) / current_price * 100
                    
                    print(f"    💰 当前价格: ¥{current_price:.2f}")
                    print(f"    🎯 月末预期价格: ¥{predicted_price:.2f}")
                    print(f"    📊 预期涨跌: {change_pct:+.2f}%")
                
                # 技术信号
                signal = self.technical_analyzer.get_trading_signal(data)
                print(f"    📊 当前技术信号: {signal}")
            else:
                print(f"    📊 基于技术分析，建议观察趋势变化")
                
        except Exception as e:
            print(f"    ❌ 预测失败: {e}")
    
    def assess_investment_risk(self, data, stock_name):
        """评估投资风险"""
        print(f"\\n  ⚖️  {stock_name} 投资风险评估:")
        
        returns = data['close'].pct_change().dropna()
        
        # VaR计算
        var_95 = np.percentile(returns, 5) * 100
        
        # 夏普比率
        excess_returns = returns.mean() * 252 - 0.03
        volatility = returns.std() * np.sqrt(252)
        sharpe_ratio = excess_returns / volatility if volatility > 0 else 0
        
        # 最大连续下跌天数
        negative_returns = returns < 0
        max_consecutive_down = 0
        current_consecutive = 0
        for is_negative in negative_returns:
            if is_negative:
                current_consecutive += 1
                max_consecutive_down = max(max_consecutive_down, current_consecutive)
            else:
                current_consecutive = 0
        
        print(f"    📉 95% VaR (单日最大损失): {var_95:.2f}%")
        print(f"    📊 夏普比率: {sharpe_ratio:.2f}")
        print(f"    📅 最大连续下跌天数: {max_consecutive_down}天")
        
        # 风险等级
        if abs(var_95) < 3 and sharpe_ratio > 0.5:
            risk_level = "🟢 低风险"
        elif abs(var_95) < 5 and sharpe_ratio > 0:
            risk_level = "🟡 中等风险"
        else:
            risk_level = "🔴 高风险"
        
        print(f"    🎯 风险等级: {risk_level}")
    
    def generate_investment_advice(self, stock, data):
        """生成投资建议"""
        print(f"\\n  💡 投资建议:")
        
        current_price = stock['price']
        pe_ratio = stock['pe_ratio']
        total_score = stock['total_score']
        
        # 投资建议
        if total_score >= 80:
            if pe_ratio <= 15:
                advice = "🟢 强烈推荐 - 优质价值股，适合中长期持有"
                position = "建议仓位: 10-15%"
            else:
                advice = "🟢 推荐买入 - 具备较好投资价值"
                position = "建议仓位: 8-12%"
        elif total_score >= 65:
            advice = "🟡 谨慎关注 - 可考虑小仓位试探"
            position = "建议仓位: 3-5%"
        else:
            advice = "🔴 暂不推荐 - 等待更好时机"
            position = "建议仓位: 0%"
        
        print(f"    {advice}")
        print(f"    📊 {position}")
        
        # 买入时机
        recent_high = data['high'].tail(20).max()
        recent_low = data['low'].tail(20).min()
        price_position = (current_price - recent_low) / (recent_high - recent_low)
        
        if price_position < 0.3:
            timing = "💰 当前处于近期低位，是较好的买入时机"
        elif price_position < 0.7:
            timing = "📊 当前价格适中，可分批建仓"
        else:
            timing = "⚠️  当前处于近期高位，建议等待回调"
        
        print(f"    {timing}")
        
        # 止损止盈
        stop_loss = current_price * 0.85
        take_profit = current_price * 1.25
        
        print(f"    🛑 建议止损价: ¥{stop_loss:.2f} (-15%)")
        print(f"    🎯 建议止盈价: ¥{take_profit:.2f} (+25%)")
    
    def generate_basic_advice(self, stock):
        """基于基本面生成建议"""
        print(f"\\n  💡 基于基本面的投资建议:")
        
        pe_ratio = stock['pe_ratio']
        market_cap = stock['market_cap']
        
        if pe_ratio <= 10 and market_cap >= 100:
            print(f"    🟢 低估值大盘股，适合价值投资")
        elif pe_ratio <= 20:
            print(f"    🟡 估值合理，可考虑配置")
        else:
            print(f"    🔴 估值偏高，建议等待回调")
    
    def generate_portfolio_advice(self, selected_stocks):
        """生成投资组合建议"""
        self.print_header("第三步：投资组合建议")
        
        total_score = sum(stock['total_score'] for stock in selected_stocks)
        
        print("📊 建议投资组合配置:")
        
        for i, stock in enumerate(selected_stocks, 1):
            weight = (stock['total_score'] / total_score) * 100 if total_score > 0 else 33.33
            risk_adjust = 1.0
            
            # 风险调整
            if stock['pe_ratio'] > 20:
                risk_adjust *= 0.8
            if stock['market_cap'] < 100:
                risk_adjust *= 0.9
                
            adjusted_weight = weight * risk_adjust
            
            print(f"\\n  {i}. {stock['code']} - {stock['name']}")
            print(f"     建议权重: {adjusted_weight:.1f}%")
            print(f"     投资理由: 综合评分{stock['total_score']:.1f}/100")
            print(f"     风险等级: {'低' if stock['pe_ratio'] <= 15 else '中等'}")
            
        print(f"\\n💰 资金配置建议:")
        print(f"  - 总仓位: 建议不超过总资金的30-40%")
        print(f"  - 分批建仓: 分2-3次买入，间隔1-2周")
        print(f"  - 止损策略: 单只股票跌幅超过15%考虑止损")
        print(f"  - 定期复查: 每月重新评估一次投资组合")
        print(f"  - 持有周期: 建议持有3-12个月")
        
        print(f"\\n🎯 投资要点:")
        print(f"  1. 这些股票都是基本面较好的优质企业")
        print(f"  2. 当前估值相对合理，具备中长期投资价值")
        print(f"  3. 建议结合大盘走势和个股技术面择时买入")
        print(f"  4. 严格执行止损策略，控制单股损失在15%以内")
        
        print(f"\\n🎉 分析完成！")
        print(f"💡 请记住：投资有风险，以上分析仅供参考，不构成投资建议")
        print(f"📊 建议结合自己的风险承受能力和投资目标做出决策")

if __name__ == "__main__":
    analyzer = CompleteInvestmentAnalyzer()
    analyzer.run_complete_analysis()
